using System;
using System.Collections.Generic;
using Castle.ActiveRecord;
using CosyTrade.Core;
using CosyTrade.Data;
using CosyTrade.Organization;
using NHibernate.Expression;

namespace CosyTrade
{
    [Addin("OrganizationSystem")]
    public class OrganizationSystem : AddinBase, IOrganizationSystem
    {
        public void UpdateCompany(Company company)
        {
            OrmDataAccess.Save(company);
        }

        public Company GetCompanyDetail(Guid companyKey)
        {
            return OrmDataAccess.FindByPrimaryKey<Company>(companyKey);
        }

        public IList<Company> GetCompanyList()
        {
            return OrmDataAccess.FindAll<Company>();
        }

        public IList<Employee> GetEmployeeList(Guid companyKey)
        {
            return OrmDataAccess.FindAll<Employee>(Expression.Eq("OnCompany.PrimaryKey", companyKey));
        }

        public void CreateEmployee(Employee employee)
        {
            using(new TransactionScope(OnDispose.Commit))
            {
                ISecuritySystem securitySys = (ISecuritySystem)CurrentAddinManager.GetAddin("SecuritySystem");
                securitySys.CreateRole(employee.MaptoRole);
                OrmDataAccess.Create(employee);
            }
         }

        public void UpdateEmployee(Employee employee)
        {
            using(new TransactionScope(OnDispose.Commit))
            {
                ISecuritySystem securitySys = (ISecuritySystem)CurrentAddinManager.GetAddin("SecuritySystem");
                securitySys.UpdateRole(employee.MaptoRole);
                OrmDataAccess.Save(employee);
            }
        }

        public void DeleteEmployee(Guid employeeKey)
        {
            OrmDataAccess.Delete(GetEmployeeDetail(employeeKey));
        }

        public Employee GetEmployeeDetail(Guid empKey)
        {
            return OrmDataAccess.FindByPrimaryKey<Employee>(empKey);
        }

        public IList<Employee> GetEmployeeList(ICriterion criterion)
        {
            return OrmDataAccess.FindAll<Employee>(new Order[] {Order.Asc("EmpNumber")}, criterion);
        }
    }
}